const app = getApp();

Page({
  data: {
    ws: null,
    message: '',
    receivedMessage: [],
    userId: null,
    roomId: null,
    isOwner: false,
    roomOwner: '',
    roomUsers: [],
    newMaxUsers: 10,
    showMaxUsersDialog: false,
    avatarCache: {},
    defaultAvatar: "https://picsum.photos/200/200",
    showChangeOwnerDialog: false,
    targetOwnerId: '',
    targetOwnerIndex: 0,
    requestingAvatars: {},
    badWords: ["你妈","你奶奶的","操","操你妈","你大爷","傻逼","你他妈","你他妈","你奶奶","死全家","日你先人","草泥马"],
    messageAvatars: {}, 
    showAvatarPopup: false,  
    currentUserId: '',
    currentScore: 0,
  submittedScores: {} // 存储已提交的评分 
  },

  onLoad(options) {
    this.setData({ roomId: options.roomId });
    this.initWebSocket();
  },
  onAvatarTap(e){
    const userId = e.currentTarget.dataset.userid;
  const { roomUsers, newMaxUsers } = this.data;

  if (roomUsers.length >= newMaxUsers) {
    this.setData({
      showAvatarPopup: true,
      currentUserId: userId
    });
  } else {
    wx.showToast({
      title: `房间人数未满（当前${roomUsers.length}/${newMaxUsers}人），无法评分`,
      icon: 'none',
      duration: 1500
    });
  }
},
  closePopup() {
    this.setData({
      showAvatarPopup: false  
    });
  },
  handlePopupAction() {
    console.log('操作用户：', this.data.currentUserId);
    this.closePopup();  
  },

  onAvatarError(e) {
    const userId = e.currentTarget.dataset.userid;
    const index = e.currentTarget.dataset.index;
    
    const avatarCache = this.data.avatarCache;
    const messageAvatars = this.data.messageAvatars;
    
    avatarCache[userId] = this.data.defaultAvatar;
    messageAvatars[index] = this.data.defaultAvatar;
    
    this.setData({
      avatarCache: avatarCache,
      messageAvatars: messageAvatars
    });
  },

  // 预加载用户头像
  preloadUserAvatars(userIds) {
    if (!userIds || !Array.isArray(userIds)) return;
    
    for (let i = 0; i < userIds.length; i++) {
      const userId = userIds[i];
      if (!userId || this.data.requestingAvatars[userId] || this.data.avatarCache[userId] !== undefined) {
        continue;
      }
      this.loadUserAvatar(userId);
    }
  },

  // 加载单个用户头像
  loadUserAvatar(userId) {
    if (!userId) return;
    
    const requestingAvatars = this.data.requestingAvatars;
    const avatarCache = this.data.avatarCache;
    
    requestingAvatars[userId] = true;
    avatarCache[userId] = this.data.defaultAvatar;
    
    this.setData({
      requestingAvatars: requestingAvatars,
      avatarCache: avatarCache
    });

    const userIdNum = Number(userId);
    const token = wx.getStorageSync('token');
    
    wx.request({
      url: `http://localhost:8080/user/avatar/${userIdNum}`,
      header: { 
        token,
        'Cache-Control': 'no-cache' // 禁止缓存，确保获取最新头像
      },
      
      success: (response) => {
        if (response.data.code === 200 && response.data.data.avatar) {
          let avatarUrl = response.data.data.avatar;
          avatarUrl = 'http://localhost:9000' + avatarUrl;
          const newAvatarCache = this.data.avatarCache;
          newAvatarCache[userId] = avatarUrl;
          
          this.setData({
            avatarCache: newAvatarCache
          }, () => {
       
            this.updateMessageAvatars(userId, avatarUrl);
    
            if (userId === this.data.userId) {
              this.syncOwnMessageAvatar(avatarUrl);
            }
          });
        }
      },
      fail: (error) => {
        console.error(`获取用户${userId}头像失败`, error);
        const failedAvatarCache = this.data.avatarCache;
        failedAvatarCache[userId] = this.data.defaultAvatar;
        this.setData({
          avatarCache: failedAvatarCache
        });
      },
      complete: () => {
        const completedRequesting = this.data.requestingAvatars;
        completedRequesting[userId] = false;
        this.setData({
          requestingAvatars: completedRequesting
        });
      }
    });
  },
  syncOwnMessageAvatar(avatarUrl) {
    const newMessageAvatars = this.data.messageAvatars;
    let hasUpdate = false;
    
    for (let i = 0; i < this.data.receivedMessage.length; i++) {
      if (this.data.receivedMessage[i].userId === this.data.userId) {
        newMessageAvatars[i] = avatarUrl;
        hasUpdate = true;
      }
    }
    
    if (hasUpdate) {
      this.setData({
        messageAvatars: newMessageAvatars
      });
    }
  },

  updateMessageAvatars(userId, avatarUrl) {
    const newMessageAvatars = this.data.messageAvatars;
    let hasUpdate = false;
    
    for (let i = 0; i < this.data.receivedMessage.length; i++) {
      if (this.data.receivedMessage[i].userId === userId) {
        newMessageAvatars[i] = avatarUrl;
        hasUpdate = true;
      
      }
    }
    
    if (hasUpdate) {
      this.setData({
        messageAvatars: newMessageAvatars
      });
    }
  },
  formatRealTime() {
    const now = new Date();
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const isToday = now.toDateString() === new Date().toDateString();
    if (isToday) {
      return `${hours}:${minutes}`;
    }
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },

  initWebSocket() {
    const token = wx.getStorageSync('token');
    if (!token) {
      console.error('Token 不存在，无法建立连接');
      wx.redirectTo({ url: '/pages/login/login' });
      return;
    }

    const userId = this.parseUserIdFromToken(token);
    this.setData({ userId });
    if (userId) {
      this.loadUserAvatar(userId); 
    }

    this.setData({
      ws: wx.connectSocket({
        url: `ws://localhost:8080/chatWebSocket/${this.data.roomId}/${userId}?token=${token}`,
        method: 'GET',
      }),
    });

    this.data.ws.onOpen(() => {
      console.log('websocket已打开');
      if (userId) {
        this.loadUserAvatar(userId);
      }
    });

    this.data.ws.onMessage((event) => {
      let messageData;
      try {
        messageData = JSON.parse(event.data);

        if (messageData.type === 'system') {
          if (messageData.message) {
            wx.showToast({ title: messageData.message, icon: 'none' });
          }
          if (messageData.isOwner !== undefined) {
            this.setData({
              isOwner: messageData.isOwner,
              roomOwner: messageData.roomOwner || '',
            });
          }
          if (messageData.userList) {
            this.setData({ roomUsers: messageData.userList });
            this.preloadUserAvatars(messageData.userList);
            if (this.data.userId && messageData.userList.indexOf(this.data.userId) === -1) {
              this.loadUserAvatar(this.data.userId);
            }
          }
        } else if (messageData.type === 'error') {
          wx.showToast({ title: messageData.message, icon: 'none' });
        } else if (messageData.type === 'history') {
          this.handleHistoryMessages(messageData);
        } else {
          const newReceivedMessage = this.data.receivedMessage.concat([messageData]);
          this.setData({
            receivedMessage: newReceivedMessage
          });
          if (messageData.userId) {
            this.loadUserAvatar(messageData.userId);
          }
        }
      } catch (e) {
        messageData = {
          userId: 'system',
          message: event.data,
          roomId: this.data.roomId,
        };
        if (messageData.message) {
          const newReceivedMessage = this.data.receivedMessage.concat([messageData]);
          this.setData({
            receivedMessage: newReceivedMessage
          });
        }
      }
      this.scrollToBottom();
    });

    this.data.ws.onClose(() => {
      console.log('websocket已关闭');
      wx.showToast({ title: '与服务器连接已断开', icon: 'none' });
    });

    this.data.ws.onError((error) => {
      console.log('websocket发生错误:', error);
      wx.showToast({ title: '连接出错，请刷新页面重试', icon: 'none' });
    });
  },

  // 处理历史消息
  handleHistoryMessages(historyData) {
    if (historyData.messages && historyData.messages.length > 0) {
      console.log(`加载 ${historyData.messages.length} 条历史消息`);
      
      const newReceivedMessage = this.data.receivedMessage.concat(historyData.messages);
      this.setData({
        receivedMessage: newReceivedMessage
      });
      
      const userIds = [];
      for (let i = 0; i < historyData.messages.length; i++) {
        const userId = historyData.messages[i].userId;
        if (userId && userIds.indexOf(userId) === -1) {
          userIds.push(userId);
        }
      }
      this.preloadUserAvatars(userIds);
      if (this.data.userId && userIds.indexOf(this.data.userId) === -1) {
        this.loadUserAvatar(this.data.userId);
      }
      
      this.scrollToBottom();
    }
  },

  // 发送消息（不变）
  sendMessage() {
    console.log('=== sendMessage 被调用 ===');
    console.log('消息内容:', this.data.message);
    console.log('消息长度:', this.data.message.length);
    console.log('trim后长度:', this.data.message.trim().length);
    console.log('WebSocket状态:', this.data.ws);

    if (!this.data.message.trim()) {
      console.log('❌ 消息为空，不发送');
      wx.showToast({ title: '消息不能为空', icon: 'none' });
      return;
    };

    var originalMsg = this.data.message;
    var  badWords = this.data.badWords;
    var filteredMsg = originalMsg;
    for (var i = 0; i < badWords.length; i++) {
      var reg = new RegExp(badWords[i], 'gi'); 
      filteredMsg = filteredMsg.replace(reg, '*'); 
    }
    console.log('过滤后消息:', filteredMsg);

    console.log('✅ 准备发送消息');

    const sendData = {
      message: filteredMsg,
      type: 'chat',
    };
    console.log('发送数据:', sendData);
    if (!this.data.ws) {
      console.log('❌ WebSocket 未连接');
      wx.showToast({ title: '连接未就绪', icon: 'none' });
      return;
    }

    this.data.ws.send({ data: JSON.stringify(sendData) });

    const newMessage = {
      userId: this.data.userId,
      message: filteredMsg,
      roomId: this.data.roomId,
      type: 'chat',
    };

    const newReceivedMessage = this.data.receivedMessage.concat([newMessage]);
    this.setData({
      receivedMessage: newReceivedMessage,
      message: '',
    });

    // 5. 发送自己的消息后，立即同步头像（避免消息显示默认图）
    if (this.data.avatarCache[this.data.userId]) {
      this.syncOwnMessageAvatar(this.data.avatarCache[this.data.userId]);
    }

    this.scrollToBottom();
  },

  // 绑定消息输入（不变）
  bindMessageInput(e) {
    console.log('输入框内容:', e.detail.value);
    this.setData({ message: e.detail.value });
  },

  // 踢人（不变）
  kickUser(e) {
    const targetUserId = e.currentTarget.dataset.user;
    wx.showModal({
      title: '提示',
      content: `确定踢出用户${targetUserId}吗？`,
      success: (res) => {
        if (res.confirm) {
          this.data.ws.send({
            data: JSON.stringify({
              type: 'kick',
              targetUserId,
            }),
          });
        }
      },
    });
  },

  // 显示修改人数上限弹窗（不变）
  showMaxUsersDialog() {
    this.setData({ showMaxUsersDialog: true });
  },

  // 绑定人数上限输入
  bindMaxUsersInput(e) {
    this.setData({ newMaxUsers: e.detail.value });
  },

  // 关闭修改人数上限弹窗
  closeMaxUsersDialog() {
    this.setData({ showMaxUsersDialog: false });
  },

  // 设置房间人数上限
  setRoomMaxUsers() {
    if (this.data.newMaxUsers < 1) {
      wx.showToast({ title: '人数上限不能小于1', icon: 'none' });
      return;
    }
    this.data.ws.send({
      data: JSON.stringify({
        type: 'setMaxUsers',
        maxUsers: this.data.newMaxUsers,
      }),
    });
    this.setData({ showMaxUsersDialog: false });
  },

  // 打开移交房主弹窗
  openChangeOwnerDialog() {
    this.setData({ showChangeOwnerDialog: true, targetOwnerIndex: 0, targetOwnerId: '' });
  },

  // 关闭移交房主弹窗
  closeChangeOwnerDialog() {
    this.setData({ showChangeOwnerDialog: false });
  },

  // 选择目标房主
  bindOwnerChange(e) {
    const index = e.detail.value;
    this.setData({
      targetOwnerIndex: index,
      targetOwnerId: this.data.roomUsers[index],
    });
  },

  // 移交房主
  changeRoomOwner() {
    if (!this.data.targetOwnerId) return;

    this.data.ws.send({
      data: JSON.stringify({
        type: 'changeOwner',
        targetUserId: this.data.targetOwnerId,
      }),
    });
    this.setData({ showChangeOwnerDialog: false });
  },

  // 判断是否为当前用户的消息
  isCurrentUser(item) {
    return item.userId == this.data.userId;
  },

  // 手动解析JWT token
  parseUserIdFromToken(token) {
    if (!token || typeof token !== 'string') {
      console.error('parseUserIdFromToken：token 必须是有效的字符串');
      return null;
    }
  
    try {
      const tokenParts = token.split('.');
      if (tokenParts.length !== 3) {
        console.error('parseUserIdFromToken：token 格式错误，不是标准 JWT');
        return null;
      }
  
      const base64Url = tokenParts[1];
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      const padLength = (4 - (base64.length % 4)) % 4;
      const paddedBase64 = base64 + '='.repeat(padLength);
  
      let decodedStr;
      try {
        decodedStr = atob(paddedBase64);
      } catch (err) {
        console.error('parseUserIdFromToken：Base64 解码失败', err);
        return null;
      }
  
      let payload;
      try {
        payload = JSON.parse(decodedStr);
      } catch (err) {
        console.error('parseUserIdFromToken：JSON 解析失败', err);
        return null;
      }
  
      const userId = payload.userId || payload.id || payload.user_id;
      if (!userId) {
        console.error('parseUserIdFromToken：token 中未找到用户 ID 字段', payload);
        return null;
      }
  
      return String(userId);
  
    } catch (error) {
      console.error('parseUserIdFromToken：解析失败', error);
      return null;
    }
  },

  // 滚动到最新消息
  scrollToBottom() {
    wx.createSelectorQuery().select('.chat-content').boundingClientRect((rect) => {
      if (rect) {
        wx.pageScrollTo({
          scrollTop: 100000,
          duration: 0,
        });
      }
    }).exec();
  },
  exitRoom() {
    if (this.data.ws) {
      this.data.ws.close();
      console.log('点击退出按钮，关闭WebSocket连接');
    }
    wx.navigateTo({
      // url: '/pages/messageList/message' 
    });
  },

  onUnload() {
    if (this.data.ws) {
      
    }
  },
  onMessage(event) {
    let messageData;
    try {
      messageData = JSON.parse(event.data);
      if (messageData.type === 'error' && messageData.message.includes('房间不存在')) {
        wx.showToast({ title: '房间不存在', icon: 'none' });
        wx.navigateBack(); 
        return;
      }
    
    } catch (e) {
 
    }
  },
  onScoreChange(e) {
    this.setData({
      currentScore: e.detail.score
    });
  },
  
  // 提交评分
  submitScore() {
    const { currentUserId, currentScore, submittedScores, token,userId = wx.getStorageSync('token') } = this.data;
  
  // 1. 本地基础校验
  if (currentScore < 1 || currentScore > 5) {
    wx.showToast({ title: '请选择1-5分的评分', icon: 'none' });
    return;
  }
  if (currentUserId === userId) {
    wx.showToast({ title: '不能给自己评分哦', icon: 'none' });
    return;
  }
  if (submittedScores[currentUserId]) {
    wx.showToast({ title: '已给该用户评分，不可重复提交', icon: 'none' });
    return;
  }
  wx.request({
    url: 'http://localhost:8080/scorings/query',
    method: 'GET',
    header: { token },
    data: { userId: currentUserId }, // 传递被评价人ID
    success: (queryRes) => {
      if (queryRes.data.code === 200) {
        // 已有评分：调用更新接口（累加分数+评价人数+1）
        const existingScoring = queryRes.data.data;
        const updateData = {
          id: currentUserId,
          scoring: existingScoring.scoring + currentScore, // 原分数+新分数
          number: existingScoring.number + 1 // 评价人数+1
        };
        this.callUpdateScoring(updateData, newSubmittedScores);
      } else if (queryRes.data.msg === '无评分记录') {
        //无评分：调用新增接口（初始分数=新分数，评价人数=1）
        const addData = {
          id: currentUserId,
          scoring: currentScore,
          number: 1
        };
        this.callAddScoring(addData, newSubmittedScores);
      } else {
        //查询接口异常
        wx.hideLoading();
        wx.showToast({ title: queryRes.data.msg || '查询失败', icon: 'none' });
      }
    },
    fail: (queryErr) => {
      wx.hideLoading();
      console.error('查询评分失败：', queryErr);
      wx.showToast({ title: '网络错误，查询失败', icon: 'none' });
    }
  });
  const newSubmittedScores = { ...submittedScores };
  newSubmittedScores[currentUserId] = currentScore;
},
callAddScoring(addData, newSubmittedScores) {
  const token = wx.getStorageSync('token');
  wx.request({
    url: 'http://localhost:8080/scorings/add',
    method: 'POST',
    header: {
      token,
      'Content-Type': 'application/json' 
    },
    data: addData,
    success: (res) => {
      wx.hideLoading();
      if (res.data.code === 200) {
        wx.showToast({ title: '评分提交成功' });
        this.setData({
          submittedScores: newSubmittedScores,
          showAvatarPopup: false,
          currentScore: 0
        });
      } else {
        wx.showToast({ title: res.data.msg || '提交失败', icon: 'none' });
      }
    },
    fail: (err) => {
      wx.hideLoading();
      console.error('新增评分失败：', err);
      wx.showToast({ title: '网络错误，提交失败', icon: 'none' });
    }
  });
  
  
},
callUpdateScoring(updateData, newSubmittedScores) {
  const token = wx.getStorageSync('token');
  wx.request({
    url: 'http://localhost:8080/scorings/update',
    method: 'POST',
    header: {
      token,
      'Content-Type': 'application/json'
    },
    data: updateData,
    success: (res) => {
      wx.hideLoading();
      if (res.data.code === 200) {
        wx.showToast({ title: '评分更新成功' });
        this.setData({
          submittedScores: newSubmittedScores,
          showAvatarPopup: false,
          currentScore: 0
        });
      }else{
        wx.showToast({ title: res.data.msg || '更新失败', icon: 'none' });
      }
    },
    fail: (err) => {
      wx.hideLoading();
      console.error('更新评分失败：', err);
      wx.showToast({ title: '网络错误，更新失败', icon: 'none' });
    }
  });
}
})